package com.zmn.mcc.cas.server.controller.cas;

import com.zmn.common.utils.captcha.GifCaptchaUtil;
import com.zmn.common.utils.cookie.CookieUtil;
import com.zmn.mcc.cas.server.CaptchaService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author duanzuocai
 * @version v1.0
 * @since 2019/1/17 16:58
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

//    @Resource
//    private RedisTemplate redisTemplate;

    @Resource
    private CaptchaService captchaService;

    /**
     * 获取Gif验证码
     *
     * @param response
     */
    @RequestMapping(value = "gif", method = RequestMethod.GET)
    public void getGifCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //告诉客户端输出的格式
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");
//        GifCaptchaUtil gifCaptcha = new GifCaptchaUtil(200, 80, new Font("宋体", Font.BOLD, 40), 100);
//        try {
//            String random = RandomUtil.getStringRandom(32);
//            String key = GifCaptchaUtil.getRediskey(random);
//            redisTemplate.opsForValue().setIfAbsent(key, gifCaptcha.getWord(), GifCaptchaUtil.TIMEOUT, TimeUnit.SECONDS);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        CaptchaService.GifCaptcha gifCaptcha = captchaService.generateGif();
        CookieUtil.addCookie(response, GifCaptchaUtil.CAPTCHE_COOKIE_KEY, gifCaptcha.getKey(), GifCaptchaUtil.TIMEOUT);
        response.getOutputStream().write(gifCaptcha.getBytes());

    }
}
